package com.lyl.syt.api;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.lyl.syt.common.helper.JwtHelper;
import com.lyl.syt.common.result.Result;
import com.lyl.syt.constant.wx.WxConstant;
import com.lyl.syt.model.user.UserInfo;
import com.lyl.syt.service.UserInfoService;
import com.lyl.syt.utils.HttpClientUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信操作接口
 */
@Api(tags = "微信登录")
@Controller
@RequestMapping("/api/ucenter/wx")
@RequiredArgsConstructor
public class WxApiController {
    private final UserInfoService userInfoService;

    @ApiOperation("微信登录回调方法")
    @GetMapping("/callback")
    public String callback(String code, String state) {
        //1. 获取临时票据
        System.out.println("code = " + code);
        //2. 获取微信的access_token
        //使用code和appid以及appscrect换取access_token
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                WxConstant.APP_ID,
                WxConstant.APP_SECRET,
                code);

        try {
            String resInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("resInfo = " + resInfo);
            //从返回字符串中获取两个值 openid 和 access_token
            JSONObject jsonObject = JSONObject.parseObject(resInfo);
            String access_token = jsonObject.getString("access_token");
            String opneid = jsonObject.getString("openid");

            //根据openid判断数据库中是否存在微信号
            boolean existSameWxUser = userInfoService.lambdaQuery()
                    .eq(UserInfo::getOpenid, opneid)
                    .exists();
            UserInfo userInfo = new UserInfo();
            if (!existSameWxUser){
                //根据 openid 和 access_token 请求微信地址，获取扫码人的信息
                String baseUserInfoUrl = "http://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, opneid);
                String resultInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("resultInfo = " + resultInfo);
                //解析用户信息
                jsonObject = JSONObject.parseObject(resultInfo);
                String nickname = jsonObject.getString("nickname");
                String headImgUrl = jsonObject.getString("headimgurl");
                opneid = jsonObject.getString("openid");
                //将扫码人的信息添加到数据库中
                userInfo.setNickName(nickname);
                userInfo.setOpenid(opneid);
                userInfo.setStatus(1);
                System.out.println("userInfo = " + userInfo);
                userInfoService.save(userInfo);
            }else {
                userInfo = userInfoService.lambdaQuery()
                        .eq(UserInfo::getOpenid, opneid).one();
            }


            Map<String,Object> map = new HashMap<>();
            String name = userInfo.getName();
            name = StrUtil.isBlank(name) ? userInfo.getNickName() : name;
            name = StrUtil.isBlank(name) ? userInfo.getPhone() : name;
            map.put("name",name);

            //判断手机号是否为空，返回openid
            if (StrUtil.isBlank(userInfo.getPhone())){
                map.put("openid",userInfo.getOpenid());
            }else {
                map.put("openid","");
            }

            // jwt 生成token
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token",token);

            //跳转到指定页面中
            return "redirect:" + WxConstant.YYGH_BASE_URL + "/wx/callback?token=" +
                    map.get("token") + "&openid=" + map.get("openid") +
                    "&name=" + URLEncoder.encode((String) map.get("name"),"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //1。 生成微信扫描二维码，返回生成二维码所需的参数
    @ApiOperation("获取微信扫描二维码")
    @GetMapping("/getLoginParam")
    @ResponseBody
    public Result<Map<String, Object>> getQrConnect() {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("appid", WxConstant.APP_ID);
            map.put("scope", "snsapi_login");
            String redirectUri = WxConstant.REDIRECT_URI;
            redirectUri = URLEncoder.encode(redirectUri, "utf-8");
            map.put("redirect_uri", redirectUri);
            map.put("state", System.currentTimeMillis() + "");
            return Result.ok(map);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return Result.fail();
        }
    }

}
